package com.youmu.xxessj

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.percent.PercentRelativeLayout
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import com.github.kittinunf.fuel.httpPost
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.youmu.xxessj.ac.MainActivity
import com.youmu.xxessj.en.User
import com.youmu.xxessj.ut.LOGINUSER
import com.youmu.xxessj.ut.REGUSER
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.layout_signin.*
import kotlinx.android.synthetic.main.layout_signup.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.singleTop
import org.jetbrains.anko.toast

class LoginActivity : AppCompatActivity() , View.OnClickListener{
    private var isSigninScreen = true

    override fun onClick(p0: View?) {
        if (p0?.id === R.id.llSignin || p0?.id === R.id.llSignup) {
            val methodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            methodManager!!.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)

        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        init()
        connect("eAz5cEclkyw95IJM8VTo20sZhGwz7IEkhdOldol4AR5JSZkVI8oEREJN6uoJD78KtG6PZ4eKxtY0lhVXRIhXaA==")
    }

    private fun init(){
        tvSignupInvoker.setOnClickListener {
            isSigninScreen = false
            showSignupForm()
        }
        tvSigninInvoker.setOnClickListener {
            isSigninScreen = true
            showSigninForm()
        }
        showSigninForm()
        //
        btnSignup.setOnClickListener {
            reg(login_m_name.text.toString(),login_m_pw.text.toString())
//            login(login_m_name.text.toString(),login_m_pw.text.toString(),"2")
        }
        //
        btnSignin.setOnClickListener {
//            startActivity(intentFor<TeacherMainActivity>().singleTop())
            login(login_s_name.text.toString(),login_s_pw.text.toString())
        }
    }
    private fun login(name :String ,pw:String){
        LOGINUSER.httpPost(listOf("username" to name,"password" to pw))
                .responseString { request, response, result ->
                    result.fold(
                            success = {
                                if (it != "[]"){
                                    val user:List<User> = Gson().fromJson(it, object : TypeToken<List<User>>() {}.type)
                                    startActivity(intentFor<MainActivity>("id" to user[0].id,"jf" to user[0].jf).singleTop())

                                }else{
                                    toast("账号或密码错误 ")
                                }
                            },
                            failure = {
                                toast("请求失败 ")
                            }
                    )
                }
    }

    private fun reg(name :String ,pw:String){
        REGUSER.httpPost(listOf("username" to name,"password" to pw))
                .responseString { request, response, result ->
                    result.fold(
                            success = {
                                if (it == "1"){
                                    toast("注册成功 ")
                                }else{
                                    toast("账号或密码错误 ")
                                }
                            },
                            failure = {
                                toast("请求失败 ")
                            }
                    )
                }
    }


    /**
     * 以下是动画切换效果
     */
    private fun showSignupForm(){
        val paramsLogin: PercentRelativeLayout.LayoutParams = llSignin.layoutParams as PercentRelativeLayout.LayoutParams
        val infoLogin = paramsLogin.percentLayoutInfo
        infoLogin.widthPercent = 0.15f
        llSignin.requestLayout()

        val paramsSignup = llSignup.layoutParams as PercentRelativeLayout.LayoutParams
        val infoSignup = paramsSignup.percentLayoutInfo
        infoSignup.widthPercent = 0.85f
        llSignup.requestLayout()

        tvSignupInvoker.visibility = View.GONE
        tvSigninInvoker.visibility = View.VISIBLE
        val translate = AnimationUtils.loadAnimation(applicationContext, R.anim.translate_right_to_left)
        llSignup.startAnimation(translate)

        val clockwise = AnimationUtils.loadAnimation(applicationContext, R.anim.rotate_right_to_left)
        btnSignup.startAnimation(clockwise)
    }

    private fun showSigninForm() {
        val paramsLogin = llSignin.layoutParams as PercentRelativeLayout.LayoutParams
        val infoLogin = paramsLogin.percentLayoutInfo
        infoLogin.widthPercent = 0.85f
        llSignin.requestLayout()


        val paramsSignup = llSignup.layoutParams as PercentRelativeLayout.LayoutParams
        val infoSignup = paramsSignup.percentLayoutInfo
        infoSignup.widthPercent = 0.15f
        llSignup.requestLayout()

        val translate = AnimationUtils.loadAnimation(applicationContext, R.anim.translate_left_to_right)
        llSignin.startAnimation(translate)

        tvSignupInvoker.visibility = View.VISIBLE
        tvSigninInvoker.visibility = View.GONE
        val clockwise = AnimationUtils.loadAnimation(applicationContext, R.anim.rotate_left_to_right)
        btnSignin.startAnimation(clockwise)
    }

    private fun connect(token: String) {


        RongIM.connect(token, object : RongIMClient.ConnectCallback() {

            /**
             * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
             * 2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
             */
            override fun onTokenIncorrect() {
                toast("链接成功")
            }

            /**
             * 连接融云成功
             * @param userid 当前 token 对应的用户 id
             */
            override fun onSuccess(userid: String) {
//                    Log.d("LoginActivity", "--onSuccess$userid")
//                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
//                    finish()
                toast("链接成功")
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            override fun onError(errorCode: RongIMClient.ErrorCode) {
                toast("链接失败")
            }
        })
    }

}
